using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using Common;
using Common.Enum;
using Common.NotifyEvent;
using MainView.MainControls;
using MainView.Windows;
using SExperiment;
using SProject;
using SProject.Paramter;
using SProject.Program;
using SWellPlate;

namespace MainView.View
{
	public partial class UCWellEdit : UserControl, IComponentConnector, IStyleConnector
	{
		public static readonly RoutedEvent OnWellPropertyChangedRoutedEvent = EventManager.RegisterRoutedEvent("OnWellPropertyChangedRoutedEvent", RoutingStrategy.Bubble, typeof(EventHandler<RoutedEventArgs>), typeof(UCWellEdit));

		public static readonly DependencyProperty IsDecryptProperty = DependencyProperty.Register("IsDecrypt", typeof(bool), typeof(UCWellEdit), new UIPropertyMetadata(true));

		private bool IsProjectSelectedChangedByUser = true;

		private bool IsProjectIsChecking;

		private ObservableCollection<ProjectEnabled> ProjectList = new ObservableCollection<ProjectEnabled>();

		private Experiment _Experiment;

		private bool isLoad;

		public bool IsDecrypt
		{
			get
			{
				return (bool)GetValue(IsDecryptProperty);
			}
			set
			{
				SetValue(IsDecryptProperty, value);
			}
		}

		public event RoutedEventHandler WellPropertyChanged
		{
			add
			{
				AddHandler(OnWellPropertyChangedRoutedEvent, value);
			}
			remove
			{
				RemoveHandler(OnWellPropertyChangedRoutedEvent, value);
			}
		}

		private void RaiseWellPropertyChanged()
		{
			RaiseEvent(new RoutedEventArgs
			{
				RoutedEvent = OnWellPropertyChangedRoutedEvent
			});
		}

		public UCWellEdit(Experiment experiment)
		{
			_Experiment = experiment;
			base.DataContext = _Experiment;
			InitializeComponent();
			_Experiment.Event += _Experiment_Event;
			ProjectManage.GetInstance().AllProjectList.CollectionChanged += AllProjectList_CollectionChanged;
			ProjectList.CollectionChanged += ProjectList_CollectionChanged;
			AddHandler(UCPlate.OnSelectionChangedRoutedEvent, new RoutedEventHandler(WellPlateSelectionChanged_RoutedEvent), true);
			ResetProjectList(_Experiment.Type);
			listProject.ItemsSource = ProjectList;
			UCWellPlateWell.SetBinding(UCPlate.HighLightProperty, new Binding("HighLight")
			{
				Source = _Experiment.ExperimentSetting
			});
			UCWellInfoSample.SetBinding(UCWellInfo.HighLightProperty, new Binding("HighLight")
			{
				Source = _Experiment.ExperimentSetting
			});
			UCWellPlateWell.Experiment = _Experiment;
			UCWellInfoSample.Targets = UCWellPlateWell.WellTargets;
			UCWellPlateWell.SetMenuItemColorSettingEnable(false);
			UCWellPlateWell.SetBinding(UCPlate.IsDecryptProperty, new Binding("IsDecrypt")
			{
				Source = this
			});
		}

		public void OnDeleteSampleAll()
		{
			foreach (ProjectEnabled project in ProjectList)
			{
				if (_Experiment.Program == null)
				{
					project.IsEnabled = true;
				}
				else
				{
					project.IsEnabled = (_Experiment.Program.Equals(project.Project.PCRProgram) ? true : false);
				}
			}
		}

		private void Root_Loaded(object sender, RoutedEventArgs e)
		{
			if (!isLoad)
			{
				isLoad = true;
				WellCell wellCell = UCWellPlateWell.WellCells.Where((WellCell s) => s.IsEnabled).FirstOrDefault();
				if (wellCell != null)
				{
					UCWellPlateWell.SelectWell(wellCell.Well);
				}
			}
		}

		public void Dispose()
		{
			ProjectManage.GetInstance().AllProjectList.CollectionChanged -= AllProjectList_CollectionChanged;
			ProjectList.CollectionChanged -= ProjectList_CollectionChanged;
			ProjectList.Clear();
			UCWellInfoSample.Dispose();
		}

		private void UCWellTargetEditor_SourceUpdated(object sender, DataTransferEventArgs e)
		{
			if (e.OriginalSource is ComboBox && ((ComboBox)e.OriginalSource).SelectedValue is SampleType)
			{
				RaiseWellPropertyChanged();
			}
			UCWellInfoSample.ReloadGridData();
		}

		private void AllProjectList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
			case NotifyCollectionChangedAction.Add:
			{
				foreach (Project project in e.NewItems)
				{
					if (project.BasicInfo.Type == _Experiment.Type && ProjectList.Where((ProjectEnabled s) => s.Project.BasicInfo.Name == project.BasicInfo.Name).Count() == 0)
					{
						ProjectList.Add(new ProjectEnabled
						{
							Project = project,
							IsEnabled = (_Experiment.Program == null || project.PCRProgram.Equals(_Experiment.Program))
						});
					}
				}
				break;
			}
			case NotifyCollectionChangedAction.Remove:
			{
				for (int num = ProjectList.Count - 1; num >= 0; num--)
				{
					if (e.OldItems.Contains(ProjectList[num].Project))
					{
						ProjectList.RemoveAt(num);
					}
				}
				break;
			}
			}
		}

		private void _Experiment_Event(object sender, EventArgs e)
		{
			PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
			if (propertyChangedEventArgsEx != null)
			{
				if (propertyChangedEventArgsEx.PropertyName == "Type")
				{
					ResetProjectList(_Experiment.Type);
					UCWellInfoSample.RefreshData();
				}
				else if (propertyChangedEventArgsEx.PropertyName == "Status" && _Experiment.Status == EExperimentStatus.Completed)
				{
					ResetProjectList(_Experiment.Type);
				}
			}
		}

		private void projectPreview_Click(object sender, RoutedEventArgs e)
		{
			Button button = sender as Button;
			if (button != null && button.DataContext != null)
			{
				ProjectEnabled projectEnabled = button.DataContext as ProjectEnabled;
				if (projectEnabled != null)
				{
					ProjectBasicInfoWindow projectBasicInfoWindow = new ProjectBasicInfoWindow();
					projectBasicInfoWindow.Owner = Utility.GetMainWindow();
					projectBasicInfoWindow.DataContext = projectEnabled.Project;
					projectBasicInfoWindow.ShowDialog();
				}
			}
		}

		private void WellPlateSelectionChanged_RoutedEvent(object sender, RoutedEventArgs e)
		{
			UCWellInfoSample.RefreshData();
			UCWellTargetEditor.SetSelectedSample(UCWellPlateWell.SelectedWells.Select((WellCell s) => s.Well).ToList());
			if (IsProjectIsChecking)
			{
				return;
			}
			IsProjectSelectedChangedByUser = false;
			IList<ProjectEnabled> list = null;
			if (UCWellPlateWell.SelectedWells.Count == 0)
			{
				foreach (ProjectEnabled project in ProjectList)
				{
					project.IsChecked = false;
					project.IsEnabled = false;
				}
				IsProjectSelectedChangedByUser = true;
				return;
			}
			if (UCWellPlateWell.SelectedProject == null)
			{
				foreach (ProjectEnabled project2 in ProjectList)
				{
					project2.IsChecked = false;
					if (_Experiment.Program == null)
					{
						project2.IsEnabled = true;
					}
					else
					{
						project2.IsEnabled = (_Experiment.Program.Equals(project2.Project.PCRProgram) ? true : false);
					}
				}
				IsProjectSelectedChangedByUser = true;
				return;
			}
			if (UCWellPlateWell.SelectedProject != null)
			{
				list = ProjectList.Where((ProjectEnabled s) => s.Project == UCWellPlateWell.SelectedProject).ToList();
			}
			foreach (ProjectEnabled project3 in ProjectList)
			{
				if (_Experiment.Program == null)
				{
					project3.IsEnabled = true;
				}
				else
				{
					project3.IsEnabled = (_Experiment.Program.Equals(project3.Project.PCRProgram) ? true : false);
				}
				if (list.Count == 1 && list[0].Project == project3.Project)
				{
					project3.IsChecked = true;
				}
				else
				{
					project3.IsChecked = false;
				}
			}
			IsProjectSelectedChangedByUser = true;
		}

		private void ProjectList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action != 0)
			{
				return;
			}
			foreach (ProjectEnabled newItem in e.NewItems)
			{
				newItem.Event += prjEnabled_Event;
			}
		}

		private void prjEnabled_Event(object sender, EventArgs e)
		{
			PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
			if (propertyChangedEventArgsEx == null || !IsProjectSelectedChangedByUser || IsProjectIsChecking || !(propertyChangedEventArgsEx.PropertyName == "IsChecked"))
			{
				return;
			}
			ProjectEnabled projectEnabled = sender as ProjectEnabled;
			if (projectEnabled == null)
			{
				return;
			}
			IsProjectIsChecking = true;
			if (projectEnabled.Project.IsEditing)
			{
				MessageBox.Show(string.Format(Utility.GetMessage("msg_project_cannot_set"), projectEnabled.Project.BasicInfo.Name), Utility.GetMessage("error"), MessageBoxButton.OK);
				projectEnabled.IsChecked = false;
				IsProjectIsChecking = false;
				return;
			}
			if (_Experiment.Type != EProjectType.AD && UCWellPlateWell.SelectedWells.Count < projectEnabled.Project.BasicOption.Items.Select((BasicOptionItem s) => s.TubeNo).Max())
			{
				MessageBox.Show(Utility.GetMessage("msg_well_not_enough"), Utility.GetMessage("error"), MessageBoxButton.OK);
				projectEnabled.IsChecked = false;
				IsProjectIsChecking = false;
				return;
			}
			if (!_Experiment.ProjectChannelMatch(projectEnabled.Project))
			{
				ChannelNotMatchWindow channelNotMatchWindow = new ChannelNotMatchWindow(_Experiment.Device.ChannelNo, projectEnabled.Project.Target.Channels);
				channelNotMatchWindow.Owner = Utility.GetMainWindow();
				channelNotMatchWindow.ShowDialog();
				projectEnabled.IsChecked = false;
				IsProjectIsChecking = false;
				return;
			}
			foreach (ProjectEnabled project in ProjectList)
			{
				if (projectEnabled.IsChecked && project != projectEnabled)
				{
					project.IsChecked = false;
				}
			}
			UpdataSelectedProject(projectEnabled.IsChecked ? projectEnabled.Project : null);
			IsProjectIsChecking = false;
		}

		public void UpdataSelectedProject(Project project)
		{
			UCWellPlateWell.SetSelectedWellProject(project);
			if (project != null && _Experiment.Program == null)
			{
				_Experiment.Program = new PCRProgram(project.PCRProgram);
			}
			if (project == null && (_Experiment.Status == EExperimentStatus.NotRunning || _Experiment.Status == EExperimentStatus.Interrupt))
			{
				IList<Well> list = _Experiment.Wells.Where((Well s) => s.Project != null).Distinct().ToList();
				if (list.Count == 0)
				{
					_Experiment.Program = null;
				}
			}
			foreach (ProjectEnabled project2 in ProjectList)
			{
				if (_Experiment.Program == null)
				{
					project2.IsEnabled = true;
				}
				else
				{
					project2.IsEnabled = (_Experiment.Program.Equals(project2.Project.PCRProgram) ? true : false);
				}
			}
			RaiseWellPropertyChanged();
		}

		public void ResetProjectList(EProjectType type)
		{
			ProjectList.Clear();
			IList<Project> prjTypeList = (from s in _Experiment.Wells
				where s.Project != null && s.Project.BasicInfo.Type == type
				select s.Project).Distinct().ToList();
			for (int i = 0; i < prjTypeList.Count; i++)
			{
				ProjectList.Add(new ProjectEnabled
				{
					Project = prjTypeList[i],
					IsEnabled = (_Experiment.Program == null || prjTypeList[i].PCRProgram.Equals(_Experiment.Program))
				});
			}
			prjTypeList = ProjectManage.GetInstance().AllProjectList.Where((Project s) => s.BasicInfo.Type == type).ToList();
			int j;
			for (j = 0; j < prjTypeList.Count; j++)
			{
				if (ProjectList.Where((ProjectEnabled s) => s.Project.BasicInfo.Name == prjTypeList[j].BasicInfo.Name).Count() == 0)
				{
					ProjectList.Add(new ProjectEnabled
					{
						Project = prjTypeList[j],
						IsEnabled = (_Experiment.Program == null || prjTypeList[j].PCRProgram.Equals(_Experiment.Program))
					});
				}
			}
		}

		public bool CanAutoStandard()
		{
			if (UCWellPlateWell.SelectedProject != null)
			{
				return UCWellPlateWell.GetSelectedSample().Count > 0;
			}
			return false;
		}

		public bool AutoStandart()
		{
			AutoStandardWindow autoStandardWindow = new AutoStandardWindow();
			autoStandardWindow.Owner = Utility.GetMainWindow();
			autoStandardWindow.SelectedWellsNum = UCWellPlateWell.SelectedWells.Count;
			if (autoStandardWindow.ShowDialog() == true)
			{
				IList<Sample> list = UCWellPlateWell.GetSelectedSample();
				switch (_Experiment.ExperimentSetting.SampleSortMode)
				{
				case ESampleSortMode.Column:
					list = list.OrderBy((Sample s) => s.Wells[0].ColumnIndex).ToList();
					break;
				case ESampleSortMode.Row:
					list = list.OrderBy((Sample s) => s.Wells[0].RowIndex).ToList();
					break;
				case ESampleSortMode.Module:
					list = (from s in list
						orderby s.Wells[0].ModelA
						orderby s.Wells[0].RowIndex
						select s).ToList();
					break;
				}
				for (int i = 0; i < list.Count / autoStandardWindow.CompoundTubeNum; i++)
				{
					double num = ((i == 0) ? 1.0 : Math.Pow(autoStandardWindow.Extent, i));
					for (int j = 0; j < autoStandardWindow.CompoundTubeNum; j++)
					{
						foreach (SampleTargetItem item in list[i * autoStandardWindow.CompoundTubeNum + j].Items)
						{
							item.SampleType = SampleType.Standard;
							if (autoStandardWindow.AutoMode == AutoStandardWindow.EAutoMode.Increase)
							{
								item.Property = ((double)autoStandardWindow.StartValue * num).ToString();
							}
							else
							{
								item.Property = ((double)autoStandardWindow.StartValue / num).ToString();
							}
						}
					}
				}
				UCWellInfoSample.ReloadGridData();
				return true;
			}
			return false;
		}

		public bool IsSelectedWell()
		{
			return UCWellPlateWell.WellCells.Where((WellCell s) => s.IsSelected && s.Well.Sample != null).Count() > 0;
		}

		private void Data_Export_Click(object sender, RoutedEventArgs e)
		{
			FrameworkElement frameworkElement = e.OriginalSource as FrameworkElement;
			if (frameworkElement == null)
			{
				return;
			}
			ProjectEnabled projectEnabled = frameworkElement.DataContext as ProjectEnabled;
			if (projectEnabled == null)
			{
				return;
			}
			if (ProjectManage.GetInstance().IsExistProjectName(projectEnabled.Project.BasicInfo.Name))
			{
				if (MessageBox.Show(string.Format(Utility.GetMessage("msg_import_project_exist"), projectEnabled.Project.BasicInfo.Name), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
				{
					return;
				}
				Project project = ProjectManage.GetInstance().GetProject(projectEnabled.Project.BasicInfo.Name);
				Project project2 = projectEnabled.Project;
				if (_Experiment.Status == EExperimentStatus.Completed)
				{
					if (project2 != null)
					{
						project.Copy(project2);
						AddProjectToManage(project, false);
					}
				}
				else if (project2 != null)
				{
					ProjectManage.GetInstance().DeleteProject(project);
					AddProjectToManage(project2, true);
				}
			}
			else
			{
				Project project3 = new Project();
				if (_Experiment.Status == EExperimentStatus.Completed)
				{
					project3.Copy(projectEnabled.Project);
				}
				else
				{
					project3 = projectEnabled.Project;
				}
				AddProjectToManage(project3, true);
			}
		}

		private void AddProjectToManage(Project p, bool shouldAdd)
		{
			if (shouldAdd)
			{
				ProjectManage.GetInstance().AddProject(p);
			}
			if (p.SaveAs(Utility.GetProjectPath()))
			{
				MessageBox.Show(Utility.GetMessage("msg_project_export_sussess"));
			}
			else
			{
				MessageBox.Show(Utility.GetMessage("msg_project_export_fail"));
			}
		}

		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
		[DebuggerNonUserCode]
		internal Delegate _CreateDelegate(Type delegateType, string handler)
		{
			return Delegate.CreateDelegate(delegateType, this, handler);
		}
	}
}
